var CustomUtils=new Object();
/*
获取浏览器信息，经过仔细测试验证过
 */
CustomUtils.Browser={
    /*
     ie
     opera
     chrome
     firefox
     safari
     */
    BrowserInfo: function () {
        var sys={};
        sys.browser = this.getBrowser().browser || "An Unknown Browser";
        sys.version = this.getBrowser().version || "0";
        sys.OS = this.getOS() || "An Unknown OS";
        if(sys.version)
            sys.version=parseFloat(sys.version);
        if(sys.browser)
            sys.browser=sys.browser.toLowerCase();
        return sys;
    },
    getOS:function(){
        if(navigator.platform.indexOf("Win")!= -1) return "windows";
        if(navigator.platform.indexOf("Mac")!= -1) return "mac";
        if(navigator.platform.indexOf("Linux")!= -1) return "linux";
        if(navigator.userAgent.indexOf("iPhone")!= -1) return "iphone/ipod";
    },
    getBrowser:function () {
        var rie = /(ie\s|trident\/7)([\w\.]+)/;
        var rTrident = /(trident)\/([\w.]+)/;
        var rFirefox = /(firefox)\/([\w.]+)/;
        var rOpera = /(opera).+version\/([\w.]+)/;
        var rNewOpera = /(opr)\/(.+)/;
        var rChrome = /(chrome)\/([\w.]+)/;
        var rSafari = /version\/([\w.]+).*(safari)/;
        var ua = navigator.userAgent.toLowerCase();
        var matchBS,matchBS2;
        //IE浏览器
        matchBS = rie.exec(ua);
        if (matchBS != null) {
            matchBS2 = rTrident.exec(ua);
            if (matchBS2 != null){
                switch (matchBS2[2]){
                    case "4.0": return { browser : "IE", version : "8" };break;
                    case "5.0": return { browser : "IE", version : "9" };break;
                    case "6.0": return { browser : "IE", version : "10" };break;
                    case "7.0": return { browser : "IE", version : "11" };break;
                    default:return { browser : "IE", version : "Undefined" };
                }
            }else{
                return {browser : "IE", version : matchBS[2] || "0" };
            }
        }
        //FireFox
        matchBS = rFirefox.exec(ua);
        if ((matchBS != null)&&(!(window.attachEvent))&&(!(window.chrome))&&(!(window.opera))) {
            return { browser : matchBS[1] || "", version : matchBS[2] || "0" };
        }
        //Opera
        matchBS = rOpera.exec(ua);
        if ((matchBS != null)&&(!(window.attachEvent))) {
            return { browser : matchBS[1] || "", version : matchBS[2] || "0" };
        }
        //Chrome
        matchBS = rChrome.exec(ua);
        if ((matchBS != null)&&(!!(window.chrome))&&(!(window.attachEvent))) {
            matchBS2 = rNewOpera.exec(ua);
            if(matchBS2 == null){
                return { browser : matchBS[1] || "", version : matchBS[2] || "0" };
            }else{
                return { browser : "Opera", version : matchBS2[2] || "0" };
            }
        }
        //Safari
        matchBS = rSafari.exec(ua);
        if ((matchBS != null)&&(!(window.attachEvent))&&(!(window.chrome))&&(!(window.opera))) {
            return { browser : matchBS[2] || "", version : matchBS[1] || "0" };
        }

        //其他情况
        return {browser :"",version:"0"};
    }
};
/*
js和css加载器
 */
CustomUtils.Loader={
    LoadedList:{},
    headEl:document.getElementsByTagName("head")[0],
    isFunction:function(f){
        return f instanceof Function;
    },
        /**
         *加载js文件
         * @param {Object} url
         */
        importJS:function(url,callback){
            var _self=this;
            var head ,
                script,
            //成功之后做的事情
                wellDone=function(){
                    _self.LoadedList[url]=true;
                    clear();
                    callback();
                },
                clear=function(){
                    script.onload=script.onreadystatechange=script.onerror=null;
                    head.removeChild(script);
                    head=script=null;
                };

            if(_self.LoadedList[url]){
                _self.isFunction(callback)&&callback();
                return;
            }
            head = CustomUtils.Loader.headEl;
            script = document.createElement("script");
            script.type = "text/javascript";

            script.onerror=function(){
                clear();
                console.log('load js file error:'+url);
            };

            if(_self.isFunction(callback)){
                //如果是IE6-IE8
                if(CustomUtils.Browser.BrowserInfo().browser=='ie' && CustomUtils.Browser.BrowserInfo().version<9){
                    script.onreadystatechange=function(){
                        //当第一次访问的时候是loaded，第二次缓存访问是complete
                        if(/loaded|complete/.test(script.readyState)){
                            wellDone();
                        }
                    }
                }else{
                    script.onload=function(){
                        wellDone();
                    }
                }
                //始终保证callback必须执行，所以需要定时器去完成，测试结果表明早期的大量的浏览器还不支持
                //timer=setTimeout(function(){
                //    wellDone();
                //},10000);
            }

            script.src = url;
            head.appendChild(script);
        },
        /**
         *加载css文件
         * @param {Object} url
         */
        importCSS:function(url,callback){
            var _self=this;
            var head,
                link,
                img,
                firefox,
                opera,
                chrome,
                poll,
            //成功之后做的事情
                wellDone=function(){
                    _self.LoadedList[url]=true;
                    clear();
                    callback();
                },
                clear=function(){
                    timer=null;
                    link.onload=link.onerror=null;
                    head=null;
                };
            if(_self.LoadedList[url]){
                _self.isFunction(callback)&&callback();
                return;
            }
            head = CustomUtils.Loader.headEl;
            link = document.createElement("link");
            link.rel="stylesheet";
            link.type = "text/css";
            link.href=url;

            link.onerror=function(){
                console.log('load css file error:'+url);
                clear();
            };
            if(_self.isFunction(callback)){
                //如果是IE系列,直接load事件
                if(CustomUtils.Browser.BrowserInfo().browser=='ie'
                    || (CustomUtils.Browser.BrowserInfo().browser=='firefox' && CustomUtils.Browser.BrowserInfo().version>8.9)
                    || CustomUtils.Browser.BrowserInfo().browser=='opera'
                    || (CustomUtils.Browser.BrowserInfo().browser=='chrome' && CustomUtils.Browser.BrowserInfo().version>19)
                    || (CustomUtils.Browser.BrowserInfo().browser=='safari' && CustomUtils.Browser.BrowserInfo().version>5.9)

                ){

                    //IE和opera浏览器用img实现
                    link.onload=function(){
                        wellDone();
                    };
                    head.appendChild(link);

                }else if(
                    (CustomUtils.Browser.BrowserInfo().browser=='chrome' && CustomUtils.Browser.BrowserInfo().version>9)
                    || (CustomUtils.Browser.BrowserInfo().browser=='safari' && CustomUtils.Browser.BrowserInfo().version>4.9)
                    || CustomUtils.Browser.BrowserInfo().browser=='firefox'
                ){

                    head.appendChild(link);
                    //如果是非IE系列
                    img=document.createElement('img');
                    img.onerror=function(){
                        img.onerror=null;
                        img=null;
                        wellDone();
                    };
                    img.src=url;

                }else{//轮询实现
                    head.appendChild(link);
                    poll=function(){
                        if(link.sheet && link.sheet.cssRules){
                            wellDone();
                        }else{
                            setTimeout(poll,300);
                        }
                    };
                    poll();
                }
            }else{
                head.appendChild(link);
            }
        },
        /**
         *异步加载所需的文件
         * @param {Array} urls
         * @param {Function} callback
         * @param {Boolean} [option=true] isOrdered 是否需要按序加载，默认是需要按序加载
         */
        BatchLoad:function(urls,callback,isOrdered){
            var _self=this,
                isOrder=!(isOrdered===false),
                isAllDone=false,
                now,
                i,
                urls= ('string'===typeof urls)?[urls]:urls;
            len=(urls instanceof Array) && urls.length,

            /**
             *根据后缀判断是js还是css文件
             * @param {Object} url
             * @param {Object} done
             */
                load=function(url, done){
                    if(/\.js(?:\?\S+|#\S+)?$/.test(url)){
                        _self.importJS(url,done);
                    }else{
                        _self.importCSS(url,done);
                    }
                },
                orderLoad=function(){
                    now=urls.shift();
                    if(now){
                        load(now,orderLoad);
                    }else{
                        callback && callback();
                    }
                };
            if(!len || len<1){
                return;
            }
            //如果有顺序
            if(isOrder){
                orderLoad();
            }else{
                //如果没有顺序加载
                for(i=0,now=0;i<len;i++){
                    load(urls[i],function(){
                        now+=1;
                        if(now==len){
                            callback && callback();
                        }
                    });
                }
            }
        },
        showPreloader:function(title,loadimage){
            //获取浏览器页面可见高度和宽度
            var _PageHeight = document.documentElement.clientHeight,
                _PageWidth = document.documentElement.clientWidth;
            //计算loading框距离顶部和左部的距离（loading框的宽度为215px，高度为61px）
            var _LoadingTop = _PageHeight > 61 ? (_PageHeight - 61) / 2 : 0,
                _LoadingLeft = _PageWidth > 215 ? (_PageWidth - 215) / 2 : 0;
            //在页面未加载完毕之前显示的loading Html自定义内容
            if(!loadimage)
                loadimage='';
            if(!title)
                title='正在加载资源......';
            var _LoadingHtml = '<div id="loader_showPreloader_loadingDiv" style="position:absolute;left:0;width:100%;height:' + _PageHeight + 'px;top:0;background:rgba(200,200,200,1);;opacity:1;filter:alpha(opacity=50);z-index:10000;">';
            _LoadingHtml+='<div style="position: absolute; left:0;right:0; top:' + _LoadingTop + 'px; width: 200px;  line-height: 57px; background: #e8e8e8; url('+ loadimage +') no-repeat scroll 5px 10px; border: 2px solid #e8e8e8;border-radius:6px;    margin: auto;    text-align: center; font-size:18px; color: #696969; font-family:\'Microsoft YaHei\';">'+title+'</div></div>';
           var _NewloadindHtml='<div id="loader_showPreloader_loadingDiv" class="ball-pulse"><div></div><div></div><div></div></div>'
           document.write(_NewloadindHtml);
        },
        hidePreloader:function(){
            var loadingMask = document.getElementById('loader_showPreloader_loadingDiv');
            loadingMask.parentNode.removeChild(loadingMask);
        }
    }